#include "syscall.h"

int myexp(int count)
{
 int i, val=1;
 for (i=0; i<count; i++ )
 {
  val = val * 10;
 }
 return val;
}
 
void itoa(char arr[],int size,int val)
{
 int i, max, dig, subval, loc;
 for (i=0; i<size; i++)
 {
  arr[i] = '\0';
 }
 for(i=1; i<=2; i++)
 {
  if((val/myexp(i))== 0)
  {
   max = i-1;
   break;
  }
 }
 subval = 0;
 loc = 0;
 for(i=max; i>=0; i--)
 {
  dig = 48 + ((val-subval) / myexp(i));
  subval = (dig-48) * myexp(max);
  arr[loc] = dig;
  loc++;
 }
 return;
}

int strLen(char* str) {
    int i = 0;
    for (i = 0;; i++) {
        if (str[i] == '\0')
            break;
    }
    return i;
}

void strCat(char* first, char* second) {

    int len1 = strLen(first);
	int len2 = strLen(second);
	int i;

    for (i = 0; i < len2; i++) {
        first[len1 + i] = second[i];
    }

    first[len1 + len2] = '\0';
}

int main(){
	char buf[60], digit[2];
	int success; 
	int machineID, i, recvID;
	machineID = GetMachineID();
	buf[0]= '\0';
	
	strCat(buf,"My machine is:\0");/*print out the machineID of this nachose instance*/
	itoa(digit, 2, machineID);
	strCat(buf,digit);
	strCat(buf,"\n\0");
    Write(buf, strLen(buf), ConsoleOutput);
	buf[0] = '\0';
	
	for(i=0; i<=4; i++){
		/*the node that broadcasting msg, can finish the loop and terminate*/
		if(machineID == 1 && i != machineID){ 
			strCat(buf,"Hi,\0");
			itoa(digit, 2, i);
			strCat(buf,digit);
			strCat(buf,"~~ I'm \0");
			itoa(digit, 2, machineID);
			strCat(buf,digit);
			strCat(buf,"\n\0");
			Write("sending message\n", 16, ConsoleOutput);
			success = Send(i,buf);/*send msg*/
			if(success == 1){
				Write("send success\n", 13, ConsoleOutput);
			}
			else{
				Write("send failed\n", 12, ConsoleOutput);
			}
			recvID = Recv(buf);/*wait for ack before sending msg to the next machine*/
			strCat(buf,"--recv from\0");
			itoa(digit, 2, recvID);
			strCat(buf,digit);
			strCat(buf,"\n\0");
			Write(buf, strLen(buf), ConsoleOutput);	
			buf[0]='\0';                       
		}
		/* other nodes that wait for incoming msg and send ack, terminate after the first loop*/
		if(machineID != 1){
			recvID = Recv(buf);
			strCat(buf,"--recv from\0");
			itoa(digit, 2, recvID);
			strCat(buf,digit);
			strCat(buf,"\n\0");
			Write(buf, strLen(buf), ConsoleOutput);
			buf[0] = '\0';

			strCat(buf,"Hi \0");
			itoa(digit, 2, recvID);
			strCat(buf,digit);
			strCat(buf,"~~ I'm \0");
			itoa(digit, 2, machineID);
			strCat(buf,digit);
			strCat(buf,", I'v got your msg\n\0");
			Write("sending message\n", 16, ConsoleOutput);
			success = Send(recvID,buf);/*reply an ack*/
			if(success == 1){
				Write("send success\n", 13, ConsoleOutput);
			}
			else{
				Write("send failed\n", 12, ConsoleOutput);
			}
			break;
		}
	}	
}
